package com.shen.accountbook.module.home.reportformsfragment;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.shen.accountbook.R;
import com.shen.accountbook.bean.AccountTypeBean;
import com.shen.accountbook.module.base.EmptyPresenterImpl;
import com.shen.accountbook.module.base.EmptyView;
import com.shen.accountbook.module.base.MVPFragment;
import com.shen.accountbook.utils.DateUtils;
import com.shen.accountbook.utils.FormatUtils;
import com.shen.accountbook.utils.PieChartUtil;
import com.shen.accountbook.utils.TestDataUtil;
import com.shen.accountbook.widget.CircleImageView;
import com.shen.accountbook.widget.NRecyclerView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.shen.accountbook.config.Constant.colorRes;
import static com.shen.accountbook.config.Constant.distance;

/**
 * author:  shen
 * date:    2018/8/27
 */
public class ReportFormsFragment extends MVPFragment<EmptyPresenterImpl> implements EmptyView {

    @BindView(R.id.layout_data_top)
    LinearLayout mLayoutDataTop;

    /** 年份 */
    @BindView(R.id.tv_year_top)
    TextView mTvYearTop;
    /** 月份 */
    @BindView(R.id.tv_month_top)
    TextView mTvMonthTop;
    /** 结余(元) */
    @BindView(R.id.tv_cash_surplus_top)
    TextView mTvCashSurplusTop;
    /** 相比上月收入 */
    @BindView(R.id.tv_cash_compared_top)
    TextView mTvCashComparedTop;

    @BindView(R.id.swipe_reportformsfragment)
    SwipeRefreshLayout mSwipe;

    /** 报表模型 */
    @BindView(R.id.chart_reportformsfragment)
    PieChart mChart;
    /** 叠在报表模型上面的布局 */
    @BindView(R.id.layout_reportformsfragment_center)
    LinearLayout mLayoutCenter;
    /** 什么报表 */
    @BindView(R.id.tv_reportformsfragment_center_title)
    TextView mTvCenterTitle;
    /** 总金额 */
    @BindView(R.id.tv_reportformsfragment_center_money)
    TextView mTvCenterMoney;
    @BindView(R.id.iv_reportformsfragment_center_img)
    ImageView mIvCenterImg;

    /** 包裹选中类型的布局 */
    @BindView(R.id.rlayout_select_item_type_reportformsfragment)
    RelativeLayout mLayoutSelectItemType;
    /** 包裹选中类型的图片的布局 */
    @BindView(R.id.layout_circle_reportformsfragment)
    RelativeLayout layoutCircle;
    /** 选中类型的图片的背景色 */
    @BindView(R.id.civ_circle_bg_reportformsfragment)
    CircleImageView mCivCircleBg;
    /** 选中类型的图片 */
    @BindView(R.id.iv_circle_img_reportformsfragment)
    ImageView mIvCircleImg;

    /** 选中的消费类型 */
    @BindView(R.id.tv_select_type_reportformsfragment)
    TextView mTvSelectType;
    /** 选中的消费类型 -- 消费的金额 */
    @BindView(R.id.tv_select_type_money_reportformsfragment)
    TextView mTvSelectTypeMoney;
    /** 选中的消费类型的消费排行榜 -- xxx消费排行榜 */
    @BindView(R.id.tv_rank_title_reportformsfragment)
    TextView mTvRankTitle;
    /** 选中的消费类型的消费排行榜 -- 列表 */
    @BindView(R.id.rv_rank_list_reportformsfragment)
    NRecyclerView mRvList;

    /** 包裹"其他类型"的布局 */
    @BindView(R.id.rlayout_item_other_reportformsfragment)
    RelativeLayout itemOther;
    /** 包裹"其他类型"的图片的布局 */
    @BindView(R.id.rlayout_other_img_reportformsfragment)
    RelativeLayout mLayoutOtherImg;
    /** "其他类型"的"金额" */
    @BindView(R.id.tv_other_money_reportformsfragment)
    TextView mTvOtherMoney;
    /** 包裹 "选中的消费类型"和"其他类型"的 布局 */
    @BindView(R.id.layout_type_data_reportformsfragment)
    LinearLayout mLayoutTypeData;


    /** true:总支出  false:总收入 -- 默认总收入true */
    private boolean TYPE = true;
    private List<AccountTypeBean.TMoneyBean> mTMoneyBeanList;
    /** 饼状图与之相对应的类型 */
    private int mReportType = 0;
    /** 类型名 */
    private String mTypeName;
    /** 类型对应的背景颜色 */
    private String mBackColor;

    private AccountTypeRankAdapter mAdapter;
    /** 假数据 -- 选中类型的 */
    private List<String> mList;

    @Override
    protected EmptyPresenterImpl createPresent(Context context) {
        return new EmptyPresenterImpl(context, this);
    }

    @Override
    public int getResId() {
        return R.layout.fragment_report_forms;
    }

    @Override
    protected void initData() {
        setTopView();
        setChart();
        setSwipe();
        setRecyclerView();
    }

    @Override
    protected void initEvent() {
        setReportData();
    }

    /**
     * 设置头部
     */
    private void setTopView(){
        mTvYearTop.setText(DateUtils.getCurYear("yyyy 年"));
        mTvMonthTop.setText(DateUtils.date2Str(new Date(), "MM"));
    }

    private void setChart(){
        PieChartUtil.initPieChart(mChart);
        mChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                if (e == null)
                    return;
                int entryIndex = (int) h.getX();
                PieChartUtil.setRotationAngle(mChart, entryIndex);
                setNoteData(entryIndex);
            }


            @Override
            public void onNothingSelected() {
                Log.i("PieChart", "nothing selected");
            }

        });
    }

    /**
     * 设置下拉
     */
    private void setSwipe(){
        mSwipe.setColorSchemeColors(colorRes, colorRes);            // 改变加载显示的颜色
        mSwipe.setDistanceToTriggerSync(distance);                  // 设置向下拉多少出现刷新
        mSwipe.setProgressViewEndTarget(false, distance);      // 设置刷新出现的位置
        mSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mSwipe.setRefreshing(false);
                PieChartUtil.setAnimate(mChart);
            }
        });
    }

    /**
     * 选中消费列表
     */
    private void setRecyclerView(){
        mRvList.setLayoutManager(new LinearLayoutManager(mContext));
        mList = new ArrayList<>();
        mAdapter = new AccountTypeRankAdapter(mContext, mList);
        mRvList.setAdapter(mAdapter);
    }

    private void setReportData() {
        AccountTypeBean typeModel = null;
        if (TYPE) {                                         /* 总支出 */
            mTvCenterTitle.setText("总支出");
            mIvCenterImg.setImageResource(R.mipmap.accountbook_output);
            typeModel = TestDataUtil.getAccountTypeBeanOut();

        } else {                                            /* 总收入 */
            mTvCenterTitle.setText("总收入");
            mIvCenterImg.setImageResource(R.mipmap.accountbook_input);
            typeModel = TestDataUtil.getAccountTypeBeanIn();
        }

        if (typeModel == null) {
            return;
        }

        mTvCashSurplusTop.setText(typeModel.getSurplus());
        mTvCashComparedTop.setText(typeModel.getScale());
        mTvCenterMoney.setText(getMoneyStr(typeModel.getTotal()));
        mTMoneyBeanList = typeModel.getT_money();

        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
        ArrayList<Integer> colors = new ArrayList<Integer>();

        if (mTMoneyBeanList != null && mTMoneyBeanList.size() > 0) {          /* 有数据时的显示 */
            mLayoutTypeData.setVisibility(View.VISIBLE);
            for (int i = 0; i < mTMoneyBeanList.size(); i++) {
                float scale = mTMoneyBeanList.get(i).getAffect_money() / typeModel.getTotal();
                float value = (scale < 0.06f) ? 0.06f : scale;
                entries.add(new PieEntry(value, PieChartUtil.getTypeDrawable(mTMoneyBeanList.get(i).getType())));
                colors.add(Color.parseColor(mTMoneyBeanList.get(i).getBack_color()));
            }
            setNoteData(0);     // 初始化默认选中第一个
        } else {                                                            /* 无数据时的显示 */
            mLayoutTypeData.setVisibility(View.GONE);
            entries.add(new PieEntry(1f));
            colors.add(0xffAAAAAA);
        }

        PieChartUtil.setPieChartData(mChart, entries, colors);
    }

    /**
     * 点击饼状图上区域后相应的数据设置
     * @param index
     */
    private void setNoteData(int index){
        mReportType = mTMoneyBeanList.get(index).getType();
        mTypeName = mTMoneyBeanList.get(index).getTypename();
        mBackColor = mTMoneyBeanList.get(index).getBack_color();

        if (TYPE) {                                                     /* 总支出 */
            mTvSelectTypeMoney.setText("-"+ getMoneyStr(mTMoneyBeanList.get(index).getAffect_money()));
        }else {                                                         /* 总收入 */
            mTvSelectTypeMoney.setText("+"+ getMoneyStr(mTMoneyBeanList.get(index).getAffect_money()));
        }

        mTvSelectType.setText(mTypeName);
        mTvRankTitle.setText(mTypeName + "排行榜");
        mCivCircleBg.setImageDrawable(new ColorDrawable(Color.parseColor(mBackColor)));
        mIvCircleImg.setImageDrawable(PieChartUtil.getTypeDrawable(mReportType));

        mList.clear();
        for(int i = 0; i < 3; i++){
            mList.add(mTypeName + i);
        }
        mAdapter.setmDatas(mList);
        mAdapter.notifyDataSetChanged();
    }


    private String getMoneyStr(double money) {
        return FormatUtils.MyDecimalFormat("##,###,###.##", money);
    }


    /**
     * 改变"总支出/总收入"
     */
    private void changeCenterType(){
        if(TYPE){
            TYPE = false;
        }else{
            TYPE = true;
        }
        setReportData();
    }


    /**
     * 选择时间
     */
    private void selectTime(){
        // 时间选择器
        new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {                       // 选中事件回调
                mTvYearTop.setText(DateUtils.date2Str(date, "yyyy 年"));
                mTvMonthTop.setText(DateUtils.date2Str(date, "MM"));

                PieChartUtil.setAnimate(mChart);
            }
        })
                .setRangDate(null, Calendar.getInstance())
                .setType(new boolean[]{true, true, false, false, false, false})
                .build()
                .show();
    }

    @OnClick({R.id.layout_reportformsfragment_center,
            R.id.layout_data_top,
            R.id.rlayout_select_item_type_reportformsfragment,
            R.id.rlayout_item_other_reportformsfragment})
    public void onViewClicked(View view) {

        switch (view.getId()) {

            case R.id.layout_reportformsfragment_center:                /* 改变"总支出/总收入" */
                changeCenterType();
                break;

            case R.id.layout_data_top:                                  /* 选择时间 */
                selectTime();
                break;

            case R.id.rlayout_select_item_type_reportformsfragment:     /* 包裹"选中类型"的布局 */
                break;

            case R.id.rlayout_item_other_reportformsfragment:           /* 包裹"其他类型"的布局 */
                break;
        }
    }
}
